public class HashBuck {
    static class Node {
        public int key;
        public int val;
        public Node next;
        public Node(int key,int val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array = new Node[10];
    public int usedSize;
    public static final double LOAD_FACTOR = 0.75;
    public void push(int key,int val) {
        Node node = new Node(key,val);
        int index = key % array.length;
        Node cur = array[index];

        while(cur != null) {
            if(cur.key == key) {
                cur.val =  val;
                return;
            }
            cur = cur.next;
        }
        //头插
        node.next = array[index];
        array[index] = node;
        usedSize++;
        if(doLoadFactor() >= 0.75) {
            //重新哈希
            reSize();
        }
    }

    /**
     * 重新哈希
     */
    private void reSize() {
        Node[] newArray = new Node[2 * array.length];
        for(int i = 0;i < array.length;i++) {
            Node cur = array[i];
            while(cur != null) {
                int index = cur.key % newArray.length;
                //记录
                Node curNext = cur.next;
                //头插到新位置
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        //返回给array
        array = newArray;
    }
    /**
     * 判断是否超过阀值
     * @return
     */
    private double doLoadFactor() {
        return usedSize * 1.0 / array.length;
    }
    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
